package fr.afcepf.atod18.jms;

import java.util.Date;

import javax.jms.Message;
import javax.jms.TextMessage;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import fr.afcepf.atod18.service.IServiceCommande;

public class JmsConsumer {
    private JmsTemplate jmsTemplate;
    private IServiceCommande serviceCommande;
    boolean hasMessage = true;

    public JmsTemplate getJmsTemplate() {
        return jmsTemplate;
    }

    public void recevoirMessage() {
        Message msg = jmsTemplate.receive();
        try {
            TextMessage textMessage = (TextMessage) msg;
            if (msg != null) {
                System.out.println("Message = " + textMessage.getText());
                traiterMessage(textMessage.getText());
            } else {
                hasMessage = false;
                System.out.println("Message null = ");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setJmsTemplate(final JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    @Scheduled(fixedRate = 120000)
    public void releverMessages() {
        System.out.println("releverMessage " + new Date());
        hasMessage = true;
        while (hasMessage) {recevoirMessage();}
    }

    public void traiterMessage(String text) {
        String tab1[] = text.split("<");
        String tab2[] = tab1[1].split(">");
        String tab3[] = tab1[0].split(" ");
        int idCommande = Integer.parseInt(tab3[1]);
        int idEtatCommande = Integer.parseInt(tab3[2]);
        System.out.println("resultat=" + tab3[0] + " idCommand=" + tab3[1]
                + " idEtatCommande=" + tab3[2] + " lib=" + tab2[0]);
        System.out.println("serviceCommande=" + serviceCommande);
        // idEtatCommande 1:En preparation 2:En Livraison 3:Livraison effectuee 4:Commande annulee
        if (idEtatCommande == 1) {
            serviceCommande.preparerCommande(idCommande, idEtatCommande);
        }
        else if (idEtatCommande == 2) {
            serviceCommande.demanderLivraison(idCommande, idEtatCommande);
        }
        else if (idEtatCommande == 3) {
            serviceCommande.finLivraison(idCommande, idEtatCommande);
        }
        else if (idEtatCommande == 4) {
            serviceCommande.annulerCommande(idCommande, idEtatCommande);
        }
    }

    /**
     * @return the serviceCommande
     */
    public IServiceCommande getServiceCommande() {
        return serviceCommande;
    }

    /**
     * @param paramServiceCommande the serviceCommande to set
     */
    public void setServiceCommande(IServiceCommande paramServiceCommande) {
        serviceCommande = paramServiceCommande;
    }
}